var contactFormDiv;
var loadingImage = false;
var loadingMessageDiv;
var loadingCountElement;
var imageArray = [];
var currentImage;
var currentTag;
var altImagesDiv;
var altImageTemplateDiv;
var ignoreNextHashEvent = true;
var initialLoad = true;

var imageCaptionAppenders = [];

var hashLinkMap;

var loadingCounter = 1;

var gallery;

$(document).ready(function() {
	setupHashChangeHandler();
	parseHash();
	loadAllTags();
	loadImages();
	setTimeout(function() { window.scrollTo(0, 1); }, 2000);
});

function loadAllTags() {
    loadAllTagsAnd(handleLoadAllTags);
}

function handleLoadAllTags(tags) {
	tags.forEach(function(tag) {
		addTag(tag, function() {
			setCurrentTag(tag);
			setHashToCurrentImageAndTag();
			loadImagesForTag(tag);
		});
	});

	addTag("about", function() {
		showContactForm();
	});

	makeHashTagActive();
}

function makeHashTagActive() {
	var tagName = hashLinkMap.get("tag");
	if (tagName) {
		setCurrentTag(tagName);
	}
}

function makeCurrentTagActive() {
	var tag = tagMenuItems.find(function(tag) {
		return tag.name == currentTag;
	});

	if (tag) {
		tag.active();
	}
}

function loadImagesForTag(tag) {
    hideContactForm();
    currentTag = tag;
    loadImagesForTagAnd(tag, handleLoadImages);
}

function parseHash() {
	hashLinkMap = new KeyValueStringParser(window.location.hash);
}

function loadImages() {
	var tag = hashLinkMap.get("tag");
	if (tag) {
		loadImagesForTag(tag);
	} else {
		loadLatestImages();
	}
}

function loadLatestImages() {
    loadLatestImagesAnd(handleLoadLatestImages);
}

function handleLoadLatestImages(images) {
	var image = images.peek();
	var tag = image.tags.peek();
	setCurrentTag(tag);
	handleLoadImages(images);
}

function setCurrentTag(tag) {
	currentTag = tag;
}

function isGalleryVisible() {
    if (gallery) {
        return true;
    }

    return false;
}

function destroyGallery() {
    if (gallery) {
        gallery.destroy();
    }
}

function handleLoadImages(images) {
    if (isGalleryVisible()) {
        destroyGallery();
    }

    var galleryElem = $('#Gallery');
    galleryElem.html(""); // detach everything... Otherwise you see the last image.

    loadingCounter = images.length;
	imageArray = [];
	for (var i = 0; i < images.length; i++) {
		var image = images[i];
        image.index = i;
		handleLoadImage(image);
	}

    galleryElem.royalSlider({
        keyboardNavEnabled: true,
        arrowsAutoHide: false,
        loop: true,
        controlNavigation: 'thumbnails',
        autoScaleSlider: true,
        autoScaleSliderWidth: 400,
        autoScaleSliderHeight: 450,
        deeplinking: {
            enabled: true
        }
    });

    gallery = galleryElem.data("royalSlider");
}

function createImageCaption(image) {
	var caption = $('<span/>');
	caption.append($('<span class="siteTitle text">daveclay.com/art</span><br/>'));
	var nameElement = $('<span/>');
	nameElement.addClass("imageName");
	nameElement.text(image.name);
	caption.append(nameElement);

	var dateElement = $('<span/>');
	dateElement.addClass("imageDate");
	dateElement.text(image.dateText);
	caption.append(dateElement);

	var properties = image.properties;
	if (properties) {
		if (properties["info"]) {
			var infoElement = $('<span/>');
			infoElement.addClass("imageInfo");
			infoElement.text(properties["info"]);
			caption.append($("<br/>"));
			caption.append(infoElement);
		}
		if (properties["print"]) {
			addPrintLink(image, caption);
		}
	}

	imageCaptionAppenders.forEach(function(imageCaptionFunc) {
		imageCaptionFunc(image, caption);
		caption.append($("<br/>"));
	});

	return caption;
}

function addPrintLink(image, caption) {
	var properties = image.properties;
	var printElement = $('<a/>');
	printElement.click(function() {
		//var messageInput = contactFormDiv.find("#message");
		//messageInput.val("Order print of " + image.name + "\n" + properties["print"]);
		showContactForm();
        hideGallery();
	});
	printElement.text(properties["print"]);
	caption.append("<br/>");
	caption.append(printElement);
}


function showInitialImage() {
	if (hashLinkMap.get("image")) {
		showHashLinkedImage();
	} else {
		var image = imageArray[0];
		handleShowImageContent(image);
	}
}

function showHashLinkedImage() {
    log("loadCounter == " + loadingCounter);
	if (loadingCounter == 0) {
		var id = hashLinkMap.get("image");
        log("hashLinkMap.get(\"image\") == " + id);
		if (id) {
			var image = findImageById(id);
            log("findImageById(" + id + ") == " + image);
			if (image) {
                if (!isGalleryVisible()) {
                    log("photoSwipeInstance.show(" + image.index + ")");
                } else {
                    log("photoSwipeInstance.setCurrentImage(" + image.index + ")");
                }
			}
		}
	}
}

function findImageById(id) {
    var theImage;
	for (var i = 0; i < imageArray.length; i++) {
		var image = imageArray[i];
		if (image.id == id) {
			theImage = image;
            break;
		}
	}
	return theImage;
}

function handleLoadImage(image) {
    calculateImageProperties(image);
    image.thumbnailLoaded = false;
    image.handleThumbnailDidLoad = function() {
        if (!this.thumbnailLoaded) {
            this.thumbnailLoaded = true;
            loadingCounter--;
            updateLoadingCount();
            handleThumbnailLoaded();
        }
    };

	var thumbnailDiv = createThumbnailDiv(image);
	image.thumbnailDiv = thumbnailDiv;

	thumbnailDiv.appendTo($("#Gallery"));

	if (imageArray.length > 0) {
		image.previous = imageArray.peek();
		image.previous.next = image;
	}
	imageArray.push(image);
}

function createThumbnailDiv(image) {
	var thumbnailDiv = $('<div/>');
	thumbnailDiv.attr("id", image.id);

	//var imageLink = $('<a>');
	//imageLink.mouseenter(function() { handleMouseEnter(image) });
	//imageLink.mouseleave(function() { handleMouseLeave(image) });
    //imageLink.click(function() { handleClick(image) });
	//thumbnailDiv.append(imageLink);

	var thumbnail = $('<a/>');
    thumbnail.addClass("rsImg");
    thumbnail.attr("data-rsTmb",image.thumbnailSrc);
	thumbnail.attr("href", image.imageFile.src);
	// thumbnail.load(function() { image.handleThumbnailDidLoad() });
	//imageLink.append(thumbnail);

    thumbnailDiv.append(thumbnail);
	return thumbnailDiv;
}

function handleThumbnailLoaded() {
    if (loadingCounter == 0 && initialLoad) {
        hideLoadingScreen();
        showInitialImage();
        makeCurrentTagActive();
		initialLoad = false;
    }
}

function updateLoadingCount() {
	var total = imageArray.length;
    var numberLoaded = total - loadingCounter;
	var percentage = Math.round((numberLoaded / total) * 100);
	loadingCountElement.text("loading " + percentage + "%");
}

function handleShowImageContent(image) {
	if (currentImage) {
		makeThumbnailInactive(currentImage);
	}

	currentImage = image;
	makeThumbnailActive(image);
	// addAltImageThumbnails(image);
}

function setHashToCurrentImageAndTag() {
	ignoreNextHashEvent = true;
	var hash = "tag:" + currentTag;
	if (currentImage) {
		hash += "/image:" + currentImage.id;
	}
	window.location.hash = hash;
	setTimeout("clearHashEvent()", 100);
}

function clearHashEvent() {
	ignoreNextHashEvent = false;
}

function doneLoadingImage() {
	loadingImage = false;
}

function handleClick(image) {
}

function handleMouseEnter(image) {
    makeThumbnailActive(image);
}

function handleMouseLeave(image) {
	makeThumbnailInactive(image);
}

function makeThumbnailActive(image) {
	if (!image) return;
	var thumbnailDiv = image.thumbnailDiv;
	thumbnailDiv.find(".thumbnail").addClass("activeThumbnail");
}

function makeThumbnailInactive(image) {
	if (!image) return;
	var thumbnailDiv = image.thumbnailDiv;
	thumbnailDiv.find(".thumbnail").removeClass("activeThumbnail");
}

function addAltImageThumbnails(image) {
	clearExistingAltImageThumbnails();
	var altImageFiles = image.allAltImageFiles;
	if (altImageFiles.length > 0) {
		addAltImageThumbnail(image.imageFile);
		for (var i = 0; i < altImageFiles.length; i++) {
			var altImageFile = altImageFiles[i];
			altImageFile.thumbnailSrc = baseImageContentServicePath + "thumb/" + image.name + "/" + altImageFile.name;
			altImageFile.src = baseImageContentServicePath + "image/" + image.name + "/" + altImageFile.name;
			addAltImageThumbnail(altImageFile);
		}
	}
}

function clearExistingAltImageThumbnails() {
	altImagesDiv.find("div").remove();
}

function addAltImageThumbnail(imageFile) {
	var altImageDiv = altImageTemplateDiv.clone();
	altImageDiv.attr("id", "alt_" + imageFile.id);
	var link = altImageDiv.find("a");
	link.click(function() { showAltImageFile(imageFile) });

	var imageTag = altImageDiv.find(".altImage");
	imageTag.attr("src", imageFile.thumbnailSrc);
	altImageDiv.removeClass("hidden");
	altImagesDiv.append(altImageDiv);
}

function hideLoadingScreen() {
    loadingMessageDiv.hide();
}

function showContactForm() {
	contactFormDiv.show();
    $('#Gallery').hide();
}

function hideContactForm() {
	contactFormDiv.hide();
    $('#Gallery').show();
}

function validateContactForm() {
	var emailInput = contactFormDiv.find("#email");
	var messageInput = contactFormDiv.find("#message");
	if (!validEmailRegex.test(emailInput.val())) {
		alert("Invalid email address.");
	} else {
		$.ajax({
			type: 'POST',
			url: baseServicePath + "contact/send",
			data: contactFormDiv.serialize(),
			success: function() {
				alert("Thank you!");
				messageInput.val("");
			}
		}).error(function() {
			alert("Sorry, an error occurred. Please try again later.");
		});

	}
	return false;
}

